const jwt = require('jsonwebtoken');
const User = require('../models/user')

const JWT_SECRET = require('../config').jwt.secret;

class AuthCtl {
  // 登录
  async login(ctx) {
    // 操作数据库一定要 await
    const{user, password} = ctx.request.body
    console.log('user111', user, password);
    if (user && password) {
      const userData = await User.findOne({user: user})

      if (!userData) {
        ctx.status = 401;
        ctx.body = { success: false, message: 'Invalid username or password' };
      }else if (userData.password !== password) {
        ctx.status = 401;
        ctx.body = { success: false, message: '账号密码错误' };
      }else {
      // 生成 Token
      const token = jwt.sign({ user, _id: userData._id }, JWT_SECRET, { expiresIn: '1h' });
        ctx.body = { 
          success: true,
          message: '登录成功',
          data: {
            userInfo: userData,
            token: token
          }
        };
      }

    } else {
      ctx.status = 401;
      ctx.body = { success: false, message: 'Invalid username or password' };
    }
  }
}

module.exports = new AuthCtl()